package com.cxm.helper.controller.admin;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.cxm.helper.pojo.dto.ConfigSaveDTO;
import com.cxm.helper.pojo.vo.ConfigVO;
import com.cxm.helper.service.ConfigService;
import com.cxm.helper.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: chenximeng
 * @date: 2022/11/21 08:42
 */
@RestController
@RequestMapping("/admin/config")
@SaCheckRole("admin")
public class ConfigAdminController {

    @Autowired
    ConfigService configService;

    @PostMapping("/list")
    public ResponseEntity<List<ConfigVO>> list(){
        return ResponseEntity.ok(configService.listConfigAndChildren());
    }

    @PostMapping("/save")
    public ResponseEntity save(@RequestBody ConfigSaveDTO config) {
        List<String> repeat;
        if (config.getId() == null) {
            repeat = configService.add(config);
            if (CollUtil.isNotEmpty(repeat)) {
                return ResponseEntity.fail(501, "数据名称重复", repeat);
            }
            return ResponseEntity.ok();
        }

        repeat =  configService.update(config);
        if (CollUtil.isNotEmpty(repeat)) {
            return ResponseEntity.fail(501, "数据名称重复", repeat);
        }
        return ResponseEntity.ok();
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity delete(@PathVariable Long id) {
        configService.deepDeleteByParentId(id);
        return ResponseEntity.ok();
    }
}
